<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
          <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="菜品名称"></el-input>
      </el-form-item>
          <el-form-item label="菜品分类" prop="categoryId">
            <el-select v-model="dataForm.categoryId"  placeholder="请选择菜品分类">
              <el-option v-for="(item,index) in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
      </el-form-item>
          <el-form-item label="菜品价格" prop="price">
          <el-input v-model="dataForm.price" placeholder="菜品价格"></el-input>
      </el-form-item>
          <el-form-item label="商品码" prop="code">
          <el-input v-model="dataForm.code" placeholder="商品码"></el-input>
          </el-form-item>

      <el-form-item label="口味配置:"  >
        <el-form-item  v-if="this.dataForm.dishFlavors.length != 0"  class="flavorBox"  >
          <div class="title">
            <span>口味名（3个字内）</span><span>口味标签（输入标签回车添加）</span>
          </div>
          <el-row   v-for="(item, index) in dataForm.dishFlavors" :key="item.id" class="flavor" :gutter="10" >
            <el-col :span="5" class="dishFlavor-name" >

              <el-input placeholder="请配置口味名" v-model="dataForm.dishFlavors[index].name"
                      ref="dishFlavorName" ></el-input>

            </el-col>
            <el-col :span="16">
              <el-input-tag v-model="dataForm.dishFlavors[index].value"></el-input-tag>
            </el-col>
            <el-col :span="3">
              <el-button  class="btn" icon="el-icon-delete-solid"  @click="delFlavor(index)"></el-button>
            </el-col>
          </el-row>

        </el-form-item>
        <el-button  type="success"  @click="addFlavore" icon="el-icon-plus"  size="small" round>添加口味</el-button>
      </el-form-item>

<!--      <el-form-item label="口味配置:" prop="disFlavors">-->
<!--          <el-form-item >-->
<!--            <div class="flavorBox">-->
<!--              <div v-if="dataForm.dishFlavors.length != 0" class="flavor"  >-->

<!--                <div class="cont">-->
<!--                  <div v-for="(item, index) in dataForm.dishFlavors" :key="item.id" class="items" v-model="dataForm.dishFlavors">-->

<!--                    <div style="margin-top: 15px;" class="dishFlavor-box">-->
<!--                      <div placeholder="口味标签"   class="dishFlavor-item" >-->

<!--                        <el-input placeholder="请配置口味名" v-model="item.name"   class="dishFlavor-name" ></el-input>-->
<!--                        <el-tag-->

<!--                            :key="tag"-->
<!--                            v-for=" tag in item.value"-->
<!--                            closable-->
<!--                            :disable-transitions="false"-->
<!--                            @close="handleClose( tag,item.value)"-->
<!--                            effect="dark">-->
<!--                          {{tag}}-->
<!--                        </el-tag>-->
<!--                        <el-input-->
<!--                            class="input-new-tag"-->
<!--                            v-if="inputVisible"-->
<!--                            v-model="inputValue"-->
<!--                            ref="saveTagInput"-->
<!--                            size="small"-->
<!--                            @keyup.enter.native="handleInputConfirm(item.value)"-->
<!--                            @blur="handleInputConfirm(item.value)"-->
<!--                        >-->
<!--                        </el-input>-->
<!--                        <el-button v-else class="button-new-tag" size="small" :type="tp" :disabled="flag" @click="showInput(),getCount(item.value)">+口味数据</el-button>-->

<!--                        <el-button  class="btn" icon="el-icon-delete-solid"  @click="delFlavor(index)"></el-button>-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </div>-->
<!--                </div>-->

<!--              </div>-->
<!--              <el-button  type="success"  @click="addFlavore" icon="el-icon-plus"  size="small" round>添加口味</el-button>-->
<!--            </div>-->
<!--         </el-form-item>-->
<!--      </el-form-item>-->


          <el-form-item label="菜品图片" prop="image">
            <el-upload
                class="avatar-uploader"
                :action="url"
                ref="upload"
                :show-file-list="false"
                :before-upload="beforeUploadHandle"
                :on-success="successHandle"
                :on-change="onChange"
                >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="imageUrl">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
      </el-form-item>
          <el-form-item label="描述信息" prop="description">
          <el-input type="textarea" v-model="dataForm.description" placeholder="描述信息" ></el-input>
      </el-form-item>
          <el-form-item :label="$t('updateStatus')" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">{{$t('updateStatusBatch')}}</el-radio>
              <el-radio :label="0">{{ $t('updateStatusBatch_stop') }}</el-radio>
            </el-radio-group>
      </el-form-item>

      </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from "js-cookie";
import {getCategoryList} from "@/api/dish/dish";

export default {
  inheritAttrs:false,//避免应用子组件根元素上


  data () {
    return {
      flag:false,
      tp:'success',
      update:false,
      inputVisible: false,
      inputValue: '',
      visible: false,
      url: '',
      num: 0,
      categoryList: [],
      imageUrl:'',
      dataForm: {
        id: '',
        name: '',
        categoryId: '',
        categoryName: '',
        dishFlavors: [],
        price: '',
        code: '',
        image: '',
        description: '',
        status: '',
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        price: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur'},
          { required: true, message: "输入不合法", trigger: 'blur',pattern:'(([1-9]{1}\\d*)(.\\d{1,2})?)|(0{1}.\\d{1,2})'}
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        dishFlavors: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        image: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
      }
    }
  },
  methods: {



    init () {
      this.visible = true

      this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`
      getCategoryList({'type': 1}).then(({data: res}) => {
        if (res.code === 0) {
          this.categoryList = res.data
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      }),
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()

        if (this.dataForm.id) {
          this.getInfo()
        }else {
         this.dataForm.dishFlavors=[]
          this.imageUrl=''
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/demo/dish/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.imageUrl=this.$urlConfig.oosUrl +res.data.image
        this.dataForm.price = String(res.data.price/100)
        this.dataForm.categoryId=res.data.categoryId
        this.dataForm.dishFlavors = res.data.dishFlavors&&res.data.dishFlavors.map(obj =>({
          ...obj,
          value:JSON.parse(obj.value),

        }))
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        let params = {...this.dataForm}
        params.status = this.dataForm.status? 1 : 0
          params.price *= 100
        params.dishFlavors=this.dataForm.dishFlavors.map(obj => ({...obj, value: JSON.stringify(obj.value)}))
        if (!this.imageUrl) {
          this.$message.error('请上传菜品图片')
          return
        }



        this.$http[!this.dataForm.id ? 'post' : 'put']('/demo/dish/', params).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),

    // 上传之前
    beforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
      this.num++
    },
    // 上传成功
    successHandle (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if (this.num === 1) {
        this.imageUrl=res.data.src+res.data.fileName

        this.dataForm.image = res.data.fileName

        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,

        })
        this.num--
      }
    },

    onChange(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },


    addFlavore(){
       this.dataForm.dishFlavors.push({'name': '', 'value': []})
    },

    delFlavor(index){
        this.dataForm.dishFlavors.splice(index, 1)
    },


  }

}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

/*.dishFlavor-box  {*/

/*  width: 700px;*/

/*}*/
/*.dishFlavor-box .dishFlavor-item  {*/

/*  border: 1px solid #c3c3c3;*/
/*  display: flex;*/
/*  justify-content: space-between;*/
/*  height: auto;*/
/*  align-items: center;*/
/*}*/
/*.dishFlavor-box .dishFlavor-item el-tag{*/
/*  display: flex;*/
/*  justify-content: space-around;*/
/*}*/

/*.dishFlavor-box .dishFlavor-item .dishFlavor-name{*/
/*  width: 150px;*/
/*}*/
/*.dishFlavor-box .dishFlavor-item .btn{*/

/*}*/


.flavorBox {
  width: 777px;
  /*background: #d3dce6;*/
  border:1px solid #DCDCDC;
  border-radius: 5px;
  padding:5px 5px;
}

.flavor {
  width: 777px;
  margin: 5px 0;

  /*border:1px solid #DCDCDC;*/
}
.dishFlavor-name {
  margin-left: 0;
}
. {
  margin-right: 0;
}

</style>